package com.ncloud.crm.dubboservice.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.dubboservice.ChnlDashboardService;
import com.ncloud.crm.mapper.ChnlDashboardMapper;


@Service(timeout = 60000)
public class ChnlDashboardServiceImpl implements ChnlDashboardService {
	private static final Logger logger = LogManager.getLogger(ChnlDashboardService.class);
	@Autowired
	public ChnlDashboardMapper mapper;
	
	//统计渠道的总销售额、当前客户数量等
	@Override
	public JSONObject getChnlCount(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		
		String userId = json.getString("userID");
		JSONObject jsonObject=new JSONObject();
		
		try{
		////渠道的总销售额
					String count=mapper.getSumFee(userId);
					if(count == null||count == ""){
						count = "0";
					}			
					//当前客户数量			
					String custNum=mapper.getCountChnlCust(userId);
					if(custNum == null||custNum == ""){
						custNum = "0";
					}
					jsonObject.put("custNum", custNum);
					//客户行业
					String industryNum=mapper.getCountChnlIndustry(userId);
					if(industryNum == null||industryNum == ""){
						industryNum = "0";
					}
					jsonObject.put("industryNum", industryNum);
					//客均销售额
					int custNums=Integer.parseInt(custNum);
					Long counts=Long.parseLong(count);
					
					double ave=0.00;
					if(custNums!=0){
						ave = (double)counts/custNums;
					}else{
						ave=0.00;
					}
					BigDecimal ss = new BigDecimal(ave/100);  
					double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
					jsonObject.put("aveCust", f1);
					//本月收入
					String thisMonthFee=mapper.getOrderFeeThisMonth(userId);
					if(thisMonthFee == null||thisMonthFee == ""){
						thisMonthFee = "0";
					}
					String thisMonthFee_d=moneyChanges(thisMonthFee);
					jsonObject.put("thisMonthFee", thisMonthFee_d);
					//上月收入
					
					String lastMonthFee=mapper.getBalanceLastMonth(userId);
					if(lastMonthFee == null||lastMonthFee == ""){
						lastMonthFee = "0";
					}
					String lastMonthFee_d=moneyChanges(lastMonthFee);
					jsonObject.put("lastMonthFee", lastMonthFee_d);
					//增长
					Long thisMonthFees=Long.parseLong(thisMonthFee);
					Long lastMonthFees=Long.parseLong(lastMonthFee);
					Long increase = thisMonthFees-lastMonthFees;
					String increase_d=moneyChanges(String.valueOf(increase));
					jsonObject.put("increase", increase_d);
					//当前销售数量
					String saleNum=mapper.getCountSaleNum(userId);
					if(saleNum == null||saleNum == ""){
						saleNum = "0";
					}
					jsonObject.put("saleNum",saleNum);
					//当前组织数量
					String countOrg=mapper.getCountOrg(userId);
					if(countOrg == null||countOrg == ""){
						countOrg = "0";
					}
					if(countOrg.equals("0")){
						countOrg="1";
					}
					jsonObject.put("countOrg",countOrg);
					//人均销售额
					int saleNums=Integer.parseInt(saleNum);
					double f2=0.00;
					if(saleNums!=0){
						double ave2 = (double)counts/saleNums;
						BigDecimal ss2 = new BigDecimal(ave2/100);  
						f2 = ss2.setScale(2,RoundingMode.HALF_UP).doubleValue();
					}					
					jsonObject.put("aveSale", f2);
					//结算单数
					String countChnlTotal=null;
					countChnlTotal=mapper.getCountChnlTotal(userId);
					if(countChnlTotal == null||countChnlTotal == ""){
						countChnlTotal = "0";
					}
					jsonObject.put("countChnlTotal", countChnlTotal);
					//待结算金额
					String sumChnlBalance=null;
					sumChnlBalance=mapper.getSumChnlBalance(userId);
					if(sumChnlBalance == null||sumChnlBalance == ""){
						sumChnlBalance = "0";
					}
					String sumChnlBalance_d=moneyChanges(sumChnlBalance);
					jsonObject.put("sumChnlBalance", sumChnlBalance_d);
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonObject;		
	}
	
		
	//从渠道销量月度统计表总查询该月数据
		@Override
		public JSONObject getChnlCountByMonth(JSONObject json){
			if(!json.containsKey("userID")){
				throw new UserException("2001","传入参数有误");
			}
			String userId = json.getString("userID");
			JSONObject jsonObject=new JSONObject();
			String year = ThisMonth().get("year");
			String thisMonths=ThisMonth().get("month");
			String thisMonthFee=null;
			String taskId = "1008";			
			List<Map<Object,Object>> countList=new ArrayList<Map<Object,Object>>();
			try{
				//该用户所在渠道
				String chnlId=mapper.getChnlIdByUserId(userId);
				//获取本月结算收入；
				thisMonthFee=mapper.getBalanceFeeThisMonth(userId);
				if(thisMonthFee==null||thisMonthFee==""){
					thisMonthFee="0";
				}
				String thisCount_d=moneyChanges(thisMonthFee);
				//获取销售列表
				countList=mapper.getSumChnlFeeByYear(taskId,year,chnlId);
				List<Object> monthList=new ArrayList<Object>();
				List<Object> datahList=new ArrayList<Object>();
				for(int i=0;i<12;i++){
					monthList.add(0);
				}
				for(int i=0;i<countList.size();i++){				
					Map<Object,Object> map=new HashMap<Object, Object>();
					map=countList.get(i);
					
					boolean flag=map.containsKey("month");
					String month = null;
					if(flag){
						month=map.get("month").toString();
						}
					
					boolean flag1=map.containsKey("chnl_income");
					String chnlIncome = null;
					String chnlIncome_d="0.00";
					if(flag1){
						chnlIncome=map.get("chnl_income").toString();
						chnlIncome_d=moneyChanges(chnlIncome);
						}
					int monthNum=Integer.parseInt(month);
					//monthList.add(month+"月");
					monthList.set(monthNum-1,chnlIncome_d);
					datahList.add(chnlIncome_d);
				}
				int monthN=Integer.parseInt(thisMonths);
				monthList.set(monthN-1,thisCount_d);
				jsonObject.put("data",monthList);
				//jsonObject.put("data",datahList);
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}
			return jsonObject;			
		}	
		
	
	//订单列表
		@Override
		public JSONArray getOrderList(JSONObject json){
			if(!json.containsKey("userID")){
				throw new UserException("2001","传入参数有误");
			}
			String userId = json.getString("userID");
			JSONArray jsonArray =new JSONArray();
			List<Map<Object,Object>> listInfo=new ArrayList<Map<Object,Object>>();
			try{
				listInfo=mapper.getOrderList(userId);	
				for(int i=0;i<listInfo.size();i++){
					Map<Object,Object> map=new HashMap<Object, Object>();
					Map<Object,Object> mapInfo=new HashMap<Object, Object>();
					map=listInfo.get(i);
					//{'订单':'','业务类型':'','客户名称':'','订单金额':'','当前状态':''},
					boolean flag=map.containsKey("order_id");
					String orderId = null;
					if(flag){
						orderId=map.get("order_id").toString();
						}
					
					boolean flag1=map.containsKey("prod_name");
					String orderType = null;
					if(flag1){
						orderType=map.get("prod_name").toString();
						}
								
					boolean flag2=map.containsKey("order_state");
					String orderState = null;
					if(flag2){
						orderState=map.get("order_state").toString();
						}
					boolean flag3=map.containsKey("cust_name");
					String custName = null;
					if(flag3){
						custName=map.get("cust_name").toString();
						}
					boolean flag4=map.containsKey("fee");
					String orderFee = null;
					String orderFee_d="0.00";
					if(flag4){
						orderFee=map.get("fee").toString();
						orderFee_d=moneyChanges(orderFee);
						}
					mapInfo.put("orderId",orderId);
					mapInfo.put("orderType",orderType);
					mapInfo.put("custName",custName);
					mapInfo.put("orderFee",orderFee_d);
					mapInfo.put("orderState",orderState);
					jsonArray.add(mapInfo);
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}
			return jsonArray;		
		}
		
		
		//销售业绩列表
		@Override
		public JSONArray getSalePerformanceList(JSONObject json){
			if(!json.containsKey("userID")){
				throw new UserException("2001","传入参数有误");
			}
			String userId = json.getString("userID");
			JSONArray jsonArray =new JSONArray();
			List<Map<Object,Object>> listInfo=new ArrayList<Map<Object,Object>>();
			try{
				listInfo=mapper.getSalePerformanceList(userId);	
				for(int i=0;i<listInfo.size();i++){
				Map<Object,Object> map=new HashMap<Object, Object>();
				Map<Object,Object> mapInfo=new HashMap<Object, Object>();
				map=listInfo.get(i);
				//{'序号':'','姓名':'','客户数':'','金额':''},
				boolean flag1=map.containsKey("sale_name");
				String saleName = null;
				if(flag1){
					saleName=map.get("sale_name").toString();
					}
							
				boolean flag2=map.containsKey("count");
				String numCust = "0";
				if(flag2){
					numCust=map.get("count").toString();
					}
				boolean flag3=map.containsKey("fee");
				String fee = null;
				String fee_d="0.00";
				if(flag3){
					fee=map.get("fee").toString();
					fee_d=moneyChanges(fee);
					}
				mapInfo.put("No",i+1);
				mapInfo.put("saleName",saleName);
				mapInfo.put("numCust",numCust);
				mapInfo.put("fee",fee_d);
				jsonArray.add(mapInfo);
			}
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}
			return jsonArray;		
		}
		

				
		//获取销售业务月统计柱状图
				@Override
				public JSONObject getProductCount(JSONObject json){
					if(!json.containsKey("userID")){
						throw new UserException("2001","传入参数有误");
					}
					String userId = json.getString("userID");
					JSONObject jsonObject=new JSONObject();
					List<Object> prodNameList=new ArrayList<Object>();		
					List<Object> saleList=new ArrayList<Object>();	

					List<Map<Object,Object>> countList=new ArrayList<Map<Object,Object>>();
					List<Map<Object,Object>> prodList=new ArrayList<Map<Object,Object>>();
				try{
					countList=mapper.getSaleFeeProduct(userId);	
					//获取销售名字列表
					saleList=mapper.getSaleNameList(userId);					
					if(saleList.size()>0){					
					//查询该用户渠道下，指定业务的信息					
					prodNameList=mapper.getProdNameList();
					for(int k=0;k<prodNameList.size();k++){
						List<Object> listData=new ArrayList<Object>();
						for(int i=0;i<saleList.size();i++){
							listData.add(0);
						}
						Map<Object,Object> maps=new HashMap<Object, Object>();
						String name=prodNameList.get(k).toString().trim();
						for(int i=0;i<countList.size();i++){
							Map<Object,Object> map=new HashMap<Object, Object>();
							
							map=countList.get(i);
							
							boolean flag1=map.containsKey("sale_name");
							String sale_name = null;
							if(flag1){
								sale_name=map.get("sale_name").toString();
								}							
							boolean flag2=map.containsKey("prod_name");
							String prodName = null;
							if(flag2){
								prodName=map.get("prod_name").toString().trim();
								}
							boolean flag=map.containsKey("fee");
							Long num=0L;
							if(flag){
								String count=map.get("fee").toString();
								if(count==null||count==""){
									num=0L;
								}else{
									num=Long.parseLong(count);
								}
							}else{
								num=0L;
							}
							String num_d=moneyChanges(String.valueOf(num));
							if(saleList.contains(sale_name)){
							if(name.equals(prodName)){
								int m=saleList.indexOf(sale_name);
								listData.set(m,num_d);
							}
							}
						}
						maps.put("data", listData);
						maps.put("name", name);
						prodList.add(maps);
					}
					jsonObject.put("prodName",prodNameList);
					jsonObject.put("data",prodList);
					jsonObject.put("name", saleList);
					}else{
						jsonObject.put("prodName",prodNameList);
						jsonObject.put("data",prodList);
						jsonObject.put("name", saleList);
					}
				}catch (Exception e) {
						e.printStackTrace();
						throw new UserException(ResultEnum.DATABASE_ERROR);
					}
					return jsonObject;			
				}						
		public Map<String,String> LastMonth(){
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, -1);
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
			String time = format.format(cal.getTime());
			String year = time.split("-")[0];
			String day = time.split("-")[1];
			Map<String,String> dateMap = new HashMap<String, String>();
			dateMap.put("year", year);
			dateMap.put("month",day);
			return dateMap;		
		}
		public Map<String, String> ThisMonth(){
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			String time = sdf.format(date);
			String year = time.split("-")[0];
			String day = time.split("-")[1];
			Map<String,String> dateMap = new HashMap<String, String>();
			dateMap.put("year", year);
			dateMap.put("month",day);
			return dateMap;		
		}	
		//分变元保留两位小数
		public String moneyChanges(String str){
			
			double values = (double)Long.parseLong(str)/100;
			BigDecimal ss = new BigDecimal(values); 
			double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
			DecimalFormat df = new DecimalFormat("######0.00"); 
			String res=df.format(f1);
			return res;
		}
}
